package com.guangzhi.weijianzhi.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.Toast;

import com.guangzhi.weijianzhi.http.HttpUrls;
import com.guangzhi.weijianzhi.service.UpImageService;
import com.guangzhi.weijianzhi.service.UploadService;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.animation.ValueAnimator.AnimatorUpdateListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

/**
 * 
 * 工具类
 * 
 * @author jrh
 * 
 */
public class CommonUtils {

	/**
	 * 上传图片
	 * 
	 * @param A
	 *            activity A
	 * 
	 * @param imgPathList
	 *            图片路径集合
	 * @param imgNameList
	 *            图片名字集合
	 */
	public static void submitImages(Activity A, ArrayList<String> imgPathList,
			ArrayList<String> imgNameList) {
		Intent intent = new Intent(A, UpImageService.class);// 七牛
		intent.putStringArrayListExtra("applylist", imgPathList);// 图片路径集合
		intent.putStringArrayListExtra("namelist", imgNameList);
		A.startService(intent);
	}

	/**
	 * 压缩图片
	 * 
	 * @param image
	 *            需要被压缩的图片
	 * @return 压缩后的图片
	 */
	public static Bitmap compressImage(Bitmap image) {
		/*** 此处是在内存中压缩，压缩之后的图片放在SD卡。 **/
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			options -= 10;// 每次都减少10
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	/**
	 * 保存图片
	 * 
	 * @param b
	 *            保存的图片
	 * @param name
	 *            name
	 * @param imgNameList
	 *            存储图片的集合 不需要时 传null
	 * @return 图片路径
	 * @throws Exception
	 */
	public static String saveImg(Bitmap b, String name,
			ArrayList<String> imgNameList) throws Exception {
		String path = Environment.getExternalStorageDirectory().getPath()
				+ File.separator;
		if (imgNameList != null) {
			imgNameList
					.add("data_" + "tid" + "_" + "uid" + "_" + name + ".jpg");

		}
		File mediaFile = new File(path + File.separator + "data_" + "tid" + "_"
				+ "uid" + "_" + name + ".jpg");
		if (mediaFile.exists()) {
			mediaFile.delete();
		}
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		mediaFile.createNewFile();
		FileOutputStream fos = new FileOutputStream(mediaFile);
		b.compress(Bitmap.CompressFormat.PNG, 100, fos);
		fos.flush();
		fos.close();
		b.recycle();
		b = null;
		System.gc();
		return mediaFile.getPath();
	}

	/**
	 * 计算图片的宽高比
	 * 
	 * @param options
	 *            Bitmap.options
	 * @param reqWidth
	 *            width
	 * @param reqHeight
	 *            height
	 * @return 缩放比
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
		}
		return inSampleSize;
	}

	/**
	 * 获取压缩后图片的路径
	 * 
	 * @param A
	 *            activity
	 * @param oldPath
	 *            oldpath
	 * @param bitmapMaxWidth
	 *            maxwidth
	 * @param uri
	 *            uri
	 * @param outputimage
	 *            输出文件
	 * @return 返回压缩后的路径
	 * @throws Exception
	 */
	public static String getThumbUploadPath(Activity A, String oldPath,
			int bitmapMaxWidth, Uri uri, File outputimage,
			ArrayList<String> imgNameList) throws Exception {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(oldPath, options);
		int height = options.outHeight;
		int width = options.outWidth;
		int reqHeight = 0;
		int reqWidth = bitmapMaxWidth;
		reqHeight = (reqWidth * height) / width;
		// 在内存中创建bitmap对象，这个对象按照缩放大小创建的
		options.inSampleSize = CommonUtils.calculateInSampleSize(options,
				bitmapMaxWidth, reqHeight);
		options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(oldPath, options);
		/**** 图片旋转角度开始 ***/
		ContentResolver cr = A.getContentResolver();
		Cursor cursor = cr.query(uri, null, null, null, null);// 根据Uri从数据库中找
		if (cursor != null) {
			cursor.moveToFirst();// 把游标移动到首位，因为这里的Uri是包含ID的所以是唯一的不需要循环找指向第一个就是了
			// String filePath =
			// cursor.getString(cursor.getColumnIndex("_data"));// 获取图片路
			String filePath = outputimage.toString();
			String orientation = cursor.getString(cursor
					.getColumnIndex("orientation"));// 获取旋转的角度
			cursor.close();
			if (filePath != null) {
				int angle = 0;
				if (orientation != null && !"".equals(orientation)) {
					angle = Integer.parseInt(orientation);
				}
				if (angle != 0) {
					// 下面的方法主要作用是把图片转一个角度，也可以放大缩小等
					Matrix m = new Matrix();
					m.postRotate(angle); // 旋转angle度
					bitmap = Bitmap.createBitmap(bitmap, 0, 0,
							bitmap.getWidth(), bitmap.getHeight(), m, true);// 从新生成图片
				}
			}
		}
		/*** 图片旋转角度结束 ****/
		Bitmap bbb = CommonUtils.compressImage(Bitmap.createScaledBitmap(
				bitmap, bitmapMaxWidth, reqHeight, false));// 压缩图片
		String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
				.format(new Date());
		return saveImg(bbb, timeStamp, imgNameList);
	}
	public static String getThumbUploadPathcomm(Activity A, String oldPath,
			int bitmapMaxWidth, File outputimage,
			ArrayList<String> imgNameList) throws Exception {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(oldPath, options);
		int height = options.outHeight;
		int width = options.outWidth;
		int reqHeight = 0;
		int reqWidth = bitmapMaxWidth;
		reqHeight = (reqWidth * height) / width;
		// 在内存中创建bitmap对象，这个对象按照缩放大小创建的
		options.inSampleSize = CommonUtils.calculateInSampleSize(options,
				bitmapMaxWidth, reqHeight);
		options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(oldPath, options);
	
		/*** 图片旋转角度结束 ****/
		Bitmap bbb = CommonUtils.compressImage(Bitmap.createScaledBitmap(
				bitmap, bitmapMaxWidth, reqHeight, false));// 压缩图片
		String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
		.format(new Date());
		return saveImg(bbb, timeStamp, imgNameList);
	}

	/**
	 * 获取图片的uri
	 * 
	 * @param A
	 * @param contentUri
	 * @return
	 */
	public static String getRealPathFromURI(Activity A, Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			// Do not call Cursor.close() on a cursor obtained using this
			// method,
			// because the activity will do that for you at the appropriate time
			Cursor cursor = A.managedQuery(contentUri, proj, null, null, null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * Toast 显示消息
	 * 
	 * @param context
	 * @param msg
	 */
	public static void showMsg(Context context, String msg) {

		Toast.makeText(context, msg, 0).show();

	}

	public static void showImage(String uri, final ImageView imageView,final ArrayList<BitmapDrawable> imags) {

		ImageLoader.getInstance().displayImage(HttpUrls.URL_QINIU + uri,
				imageView, new ImageLoadingListener() {

					@Override
					public void onLoadingStarted(String imageUri, View view) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {

						imageView.setImageBitmap(null);
						// imageView.setBackgroundDrawable(null);
						BitmapDrawable bd = new BitmapDrawable(loadedImage);

						imageView.setBackgroundDrawable(bd);
						imags.add(bd);
					}

					@Override
					public void onLoadingCancelled(String imageUri, View view) {
						// TODO Auto-generated method stub

					}
				});
	}
	public static void showBgImage(String uri, final ImageView imageView) {
		
		ImageLoader.getInstance().displayImage(HttpUrls.URL_QINIU + uri,
				imageView, new ImageLoadingListener() {
			
			@Override
			public void onLoadingStarted(String imageUri, View view) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLoadingFailed(String imageUri, View view,
					FailReason failReason) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLoadingComplete(String imageUri, View view,
					Bitmap loadedImage) {
				
				imageView.setImageBitmap(null);
				// imageView.setBackgroundDrawable(null);
				BitmapDrawable bd = new BitmapDrawable(loadedImage);
				
				imageView.setBackgroundDrawable(bd);
			}
			
			@Override
			public void onLoadingCancelled(String imageUri, View view) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	public static int getHeight(Context context) {

		DisplayMetrics dm = new DisplayMetrics();

		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(dm);

		int w = dm.widthPixels;

		int h = dm.heightPixels;
		return h;
	}

	public static void showDfImage(String url, ImageView iv) {
		ImageLoader.getInstance().displayImage(HttpUrls.URL_QINIU + url,
				iv);
	}
	
    public static  Bitmap getimage(String srcPath) {  
        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了  
        newOpts.inJustDecodeBounds = true;  
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空  
          
        newOpts.inJustDecodeBounds = false;  
        int w = newOpts.outWidth;  
        int h = newOpts.outHeight;  
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为  
        float hh = 800f;//这里设置高度为800f  
        float ww = 480f;//这里设置宽度为480f  
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可  
        int be = 1;//be=1表示不缩放  
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
            be = (int) (newOpts.outWidth / ww);  
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
            be = (int) (newOpts.outHeight / hh);  
        }  
        if (be <= 0)  
            be = 1;  
        newOpts.inSampleSize = be;//设置缩放比例  
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了  
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩  
    }  
    
	public static  void startScAm(final View lay, int nextInt) {
		// TODO Auto-generated method stub
		ObjectAnimator so = ObjectAnimator.ofFloat(lay, "so", 1.0f, 1.1f, 1.0f,
				0.9f, 1.0f);
		so.setDuration(2000);
		so.setRepeatCount(1);
		so.setRepeatMode(Animation.REVERSE);
		so.setStartDelay(nextInt);
		so.start();
		so.addUpdateListener(new AnimatorUpdateListener() {

			@SuppressLint("NewApi")
			@Override
			public void onAnimationUpdate(ValueAnimator arg0) {
				// TODO Auto-generated method stub
				float value = (Float) arg0.getAnimatedValue();
				lay.setScaleX(value);
				lay.setScaleY(value);

			}
		});
	}
}
